//
//  addCityTableViewController.m
//  SmileWeather
//
//  Created by 申浩光 on 15/9/28.
//  Copyright (c) 2015年 陶天海. All rights reserved.
//

#import "addCityTableViewController.h"

@interface addCityTableViewController ()<UISearchResultsUpdating>
@property (nonatomic, strong) UISearchController *searchController;
@property (strong,nonatomic) NSMutableArray  *searchList;
@end

@implementation addCityTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    
    _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    
    _searchController.searchResultsUpdater = self;
    
    _searchController.dimsBackgroundDuringPresentation = NO;
    
    _searchController.hidesNavigationBarDuringPresentation = NO;
    
    _searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
    _searchController.searchBar.delegate = self;
    self.tableView.tableHeaderView = self.searchController.searchBar;
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"mycell"];
    [[weatherHandle shareWetherHandle] cityName];
    NSLog(@"%@",[[weatherHandle shareWetherHandle]brr]);

    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"mycell"];

    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"回到顶部" style:UIBarButtonItemStyleDone target:self action:@selector(goTopAction:)] ;
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(dismissSelf:)] ;
     self.arr = [[NSMutableArray alloc] init];
    
}
-(void)goTopAction:(id)sender

{
    [self.tableView setContentOffset:CGPointMake(0, -12) animated:YES];
}

-(void)dismissSelf:(id)sender
{   [[weatherHandle shareWetherHandle] showHud:self title:@"请稍后" selector:@selector(relode) arg:nil targetView:self.tableView];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    if (self.searchController.active) {
        return [self.searchList count];
    }else{
        return [[PlayerDataBase shareDataBase] selegetAllFromCityNameTable].count;
    }
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSString *str = searchBar.text;

    [[PlayerDataBase shareDataBase] createTables];
    if (str==nil) {
        return;
    }else{
    [[PlayerDataBase shareDataBase] insertcityNameTable:str];
    [self.searchController.searchBar resignFirstResponder];
        [self.tableView reloadData];}
  }
//seacherBar刚开始输入时
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    searchBar.showsCancelButton = YES;
    for (id cc in [searchBar subviews]) {
        if ([cc isKindOfClass:[UIButton class]]) {
            UIButton *btn = (UIButton*)cc;
            [btn setTitle:@"取消" forState:(UIControlStateNormal)];
        
        }
        
    }
    return YES;
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    searchBar.showsCancelButton = NO;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    
    [searchBar resignFirstResponder];
    [self setsearchContrlloerHidden:YES];

}

//seacherBar内容改变
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    if (_searchDC.searchBar.text.length == 0) {
        [self setsearchContrlloerHidden:YES];
    }else{
        [self setsearchContrlloerHidden:NO];
    }
}
//下拉列表的内容
- (void)setsearchContrlloerHidden:(BOOL)hidden{
    NSInteger height = hidden ?0 :180;
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.2];
    [_seacherController.view setFrame:CGRectMake(30, 36, 200, height)];
      [UIView commitAnimations];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
  

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.searchController.active) {
        NSString *cityName = self.searchList[indexPath.row];
        NSLog(@"%@fjahjfhjahfhjfa hfjkasjjafka",cityName);
        [[NSUserDefaults standardUserDefaults]setObject:cityName forKey:@"city"];
        [[PlayerDataBase shareDataBase] insertcityNameTable:cityName];
        [[weatherHandle shareWetherHandle] relodeData];
        [tableView reloadData];
    }else{
        
        NSString *cityName = [[PlayerDataBase shareDataBase]selegetAllFromCityNameTable][indexPath.row];
        
        [[NSUserDefaults standardUserDefaults]setObject:cityName forKey:@"city"];
        [tableView reloadData];
        [[weatherHandle shareWetherHandle] relodeData];
    }
    

        
    [[weatherHandle shareWetherHandle] showHud:self title:@"请稍后..." selector:@selector(relode) arg:nil targetView:tableView];
    
   
    
}
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    NSString *searchString = [self.searchController.searchBar text];
    
    NSPredicate *preicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", searchString];
    
    if (self.searchList!= nil) {
        [self.searchList removeAllObjects];
    }
    //过滤数据
    self.searchList= [NSMutableArray arrayWithArray:[[weatherHandle shareWetherHandle].brr filteredArrayUsingPredicate:preicate]] ;
    //刷新表格
    
    [self.tableView reloadData];
}

- (void)relode{
    [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([tableView isEqual:self.searchDC.searchBar])
    {
        return 100;
    }
    else
    {
        return 40;
    }
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"mycell" forIndexPath:indexPath];
    if (self.searchController.active) {
        [cell.textLabel setText:self.searchList[indexPath.row]];
        
    }else{
        
        cell.textLabel.text = [[PlayerDataBase shareDataBase] selegetAllFromCityNameTable][indexPath.row];
    }
    
    return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
  
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        
        NSString *cityName = [[PlayerDataBase shareDataBase]selegetAllFromCityNameTable][indexPath.row];
        [[PlayerDataBase shareDataBase] deleteCityWithCityName:cityName];
      [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
 
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.tableView endEditing:YES];
    [self.view endEditing:YES];
}
- (void)viewWillAppear:(BOOL)animated{
    [self setsearchContrlloerHidden:YES];
}




@end
